import { createRouter, createWebHistory } from 'vue-router';
import { storeToRefs } from 'pinia';
import useUserInfo from '@/stores/userInfo';
import { initFrontEndControlRoutes } from '@/utils/permission';
import type { RouteRecordRaw, RouteLocationNormalized } from 'vue-router';

// 登录
import loginRouter from './modules/login';
// 首页
import homeRouter from './modules/home';
// 面试专区
import interviewRouter from './modules/interview';
// 即时通讯
import chatRouter from './modules/chat';
// 权限管理
import systemRouter from './modules/system';
// 功能
import funRouter from './modules/fun';
// 地图
import mapRouter from './modules/map';
// 401页面
import noPowerRouter from './modules/noPower';
// 404页面
import notFoundRouter from './modules/notFound';

// 静态路由
export const constantRoutes: Array<RouteRecordRaw> = [loginRouter, homeRouter, interviewRouter, noPowerRouter, notFoundRouter];
// 动态路由
export const asyncRoutes: Array<RouteRecordRaw> = [chatRouter, systemRouter, funRouter, mapRouter];

const router = createRouter({
	history: createWebHistory(),
	routes: [...constantRoutes],
});

// 判断页面是否刷新
let isRefresh = true;

// 页面刷新时
const handleRenovate = (to: RouteLocationNormalized) => {
	isRefresh = false;
	initFrontEndControlRoutes();
	return router.push(to.fullPath);
};

// 页面未刷新
// 白名单
const whiteList = ['/login'];
const handleMount = (to: RouteLocationNormalized) => {
	// 用户信息
	const stores = useUserInfo();
	const { userInfo } = storeToRefs(stores);

	// 没有登录 且 路由不在白名单之中
	if (!whiteList.includes(to.path) && !userInfo.value?.token) router.push('/login');

	// 录且跳转到登录页时
	if (userInfo.value?.token && to.path === '/login') router.push('');
};
// 路由加载前
router.beforeEach(to => {
	isRefresh ? handleRenovate(to) : handleMount(to);
});

export default router;
